<template>
  <el-carousel :interval="5000" height="40vh" indicator-position="inside">

    <el-carousel-item v-for="(option, index) in chartOptions" :key="index" style="height: 400px">
      <div :id="'chart-' + index" style="width: 100%; height: 80%;"></div>
    </el-carousel-item>

  </el-carousel>
</template>

<script setup>
import { onMounted, ref, reactive, nextTick } from 'vue';
import * as echarts from 'echarts';
import http from '../../http';

const charts = ref([]);
const chartOptions = reactive([
  {
    title: '总学习时长',
    xAxisData: [19, 2, 3, 42, 8, 12, 34, 11, 6, 36],
    yAxisData: [34152, 33145, 31425, 26514, 24516, 20131, 19821, 18723, 18555, 16263],
    apiUrl: '/api/study-duration'
  },
  {
    title: '总课程平均分',
    xAxisData: [15, 22, 34, 4, 1, 13, 25, 16, 6, 31],
    yAxisData: [90, 87, 86, 82, 80, 78, 77, 76, 72, 70],
    apiUrl: '/api/course-average'
  },
  {
    title: '总活跃人数',
    xAxisData: [1, 21, 13, 23, 8, 22, 14, 34, 7, 46],
    yAxisData: [21, 19, 17, 13, 13, 12, 10, 9, 7, 5],
    apiUrl: '/api/active-users'
  }
]);

//Fetch data from API and update chart data
const fetchData = async (chartOption) => {
  try {
    const response = await http.get(chartOption.apiUrl);
    console.log(response);
    chartOption.yAxisData = response;  
  } catch (error) {
    console.error('API call failed:', error);
  }
};

onMounted(async () => {
  nextTick(() => {
    for (const option of chartOptions) {
      // 先不请求数据
      // await fetchData(option);
      const chart = echarts.init(document.getElementById('chart-' + charts.value.length));
      chart.setOption({
        title: {
          text: option.title,
          left: 'center'
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: option.xAxisData,
          name: '班级id', 
          nameLocation: 'end' 
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: option.yAxisData,
          type: 'bar'
        }]
      });
      charts.value.push(chart);
    }
  })
});

</script>

<style scoped>
.el-carousel__container {
  background-color: #FFF;
    width: 100%;
}
</style>